<?php
//创建Server对象，监听 127.0.0.1:9501 端口
$server = new Swoole\Server('127.0.0.1', 9501);

// //task进程的数量
$server->set(['task_worker_num' => 4]);

//监听连接进入事件
$server->on('Connect', function ($server, $fd) {
    echo "客户端连接成功: Connect.\n";
});

//监听数据接收事件
$server->on('Receive', function ($server, $fd, $from_id, $data) {
	// jsondecode解码
	$req = json_decode($data, true);
	// 验证签名
	$action = $req['action'];
    $token = $req['token'];
    $timestamp = $req['timestamp'];
	
	$key = 'MYgGnQE33ytd2jDFADS39DSEWsdD24sK';  // appid
	
	if (time() - $timestamp > 180) {
        $res['code'] = '已超时';
		$res['result'] = 'failed';
        $server->send($fd, json_encode($res));  // 返回信息给客户端
        exit;
    }
	$token_get = md5($action.$timestamp.$key);
	
	if ($token != $token_get) {
        $res['msg'] = '非法提交';
		$res['result'] = 'failed';
        $server->send($fd, json_encode($res));
        exit;
    }
	// 验签通过以后
	$res['result'] = 'success';
    $server->send($fd, json_encode($res)); // 【同步】返回消息给客户端 告诉已经在处理或处理完成
	$server->task($data);  // 执行【异步】任务
	
	
    //$server->send($fd, "Server接收到了客户端发来的指令: " . $data);
});

// 接收异步请求  处理任务  $server->task($data)
$server->on('Task', function ($server, $fd) {
   $redis = new \Redis();
   $redis->connect('127.0.0.1', 6379);
   
   swoole_timer_tick(1000, function($timer) use ($redis) { // 启用定时器，每1秒执行一次
		
		$email = $redis->lpop('wait_handle_email_list'); // 从队列里取邮件 然后处理
		if($email){
			// 省略发送邮件的业务逻辑
			sleep(2);
			echo $email . '发送成功' . PHP_EOL;
		}else{
			swoole_timer_clear($timer); // 停止定时器
            echo "Emaillist出队完成";
		}
   });
});

//监听连接关闭事件
$server->on('Close', function ($server, $fd) {
    echo "Client: Close.\n";
});

//启动服务器
$server->start(); 
